const express= require('express');
const common = require('../../../libs/common');
const reg = require('../../../libs/reg');
const mailFn = require('./mail');

let router = express.Router();
module.exports = router;

router.post('/',(req,res)=>{
    
    let {mail} = req.body;
    // 验证格式
    if(!reg.mailReg.test(mail)){
        let mailData = {
            status: 2,
            errMsg:'Email error'
        }
        res.send(mailData)
    }else{
        // 判断库里是否有这个邮箱  有=》查看最后一次发送的时间  没有=》新增这个邮箱 记录最后一次发送的时间
        req.db.query(`SELECT last_send_time FROM send_mail WHERE mail='${mail}'`, (err, data) => {
            if (err) {
                res.sendStatus(500);
            } else if (data == 0) {
                let code = common.code();
                req.db.query(`INSERT INTO send_mail (mail,last_send_time,code,b_use) VALUES ('${mail}','${common.timestamp()}','${code}',0)`,(err,data)=>{
                    if(err){
                        res.sendStatus(500);
                    }else{
                        let mailData = {
                            status: 1
                        }
                        mailFn(`${mail}`,'Auth code',`${code}`,function(){
                            res.send(mailData)
                        })
                    }
                })
            } else{
                // 如果两次发送间隔不到60S 则提示 稍后发送
                if((common.timestamp()-data[0].last_send_time)>1){
                    let code = common.code();
                    req.db.query(`UPDATE send_mail SET last_send_time=${common.timestamp()},code=${code},b_use=0 WHERE mail='${mail}'`,(err,data)=>{
                        if(err){
                            res.sendStatus(500);
                        }else{
                            let mailData = {
                                status: 1
                            }
                            mailFn(`${mail}`,'Auth code',`${code}`,function(){
                                res.send(mailData)
                            })
                        }
                    })
                }else{
                    let mailData = {
                        status: 2,
                        errMsg:'Please send it later'
                    }
                    res.send(mailData)
                }
            }
        })
    }
})
